package com.daxt.controller.accept;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.result.*;
import com.daxt.common.util.DateUtil;
import com.daxt.mapper.accept.ArchivesAcceptLogMapper;
import com.daxt.mapper.sys.ArchivesClassMapper;
import com.daxt.model.dic.SystemConfigType;
import com.daxt.model.ftp.Ftp;
import com.daxt.model.service.accept.vo.ArchivesAcceptLog;
import com.daxt.model.service.archives.result.ArchivesEditResearchResult;
import com.daxt.model.service.archives.vo.ArchivesClass;
import com.daxt.model.service.archives.vo.ArchivesEditResearch;
import com.daxt.service.ArchivesAcceptService;
import com.daxt.utils.FtpUtil;
import com.daxt.utils.file.ToPdfUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "档案接口调用")
@RestController
@RequestMapping("/accept")
public class ArchivesAcceptController {

    @Autowired
    private ArchivesAcceptService acceptService;
    @Autowired
    private ArchivesAcceptLogMapper logMapper;
    @Autowired
    private ArchivesClassMapper archivesClassMapper;

    @ApiOperation("同步质保资料分类")
    @PostMapping("/syncZbClass")
    public Result<String> syncZbClass(){

        acceptService.syncZBClass();

        return  ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }

    @ApiOperation("归档文水政务信息系统数据")
    @PostMapping("/finishedBusinessInfo")
    public Result<String> finishedBusinessInfo(@ApiParam("开始时间") @RequestParam(value = "startTime") String startTime,@ApiParam("开始时间") @RequestParam("endTime") String endTime){
        ArchivesAcceptLog acceptLog=new ArchivesAcceptLog();
        acceptLog.setType("ws");
        acceptLog.setCreateTime(DateUtil.getCurrentTime(DateUtil.DateFormat.YYYY_MM_DD_HH_mm_ss));
        try{
            String code = acceptService.getWsAccept(startTime,endTime) ;
            /*if(!"200".equals(code)){
                acceptLog.setDescribes(startTime+"至"+endTime+"，的数据获取失败");
                acceptLog.setState("0");
                logMapper.insert(acceptLog);
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "接口调用失败", null);
            }*/

            if("200".equals(code)){

            }else if ("201".equals(code)){
                acceptLog.setDescribes(startTime+"至"+endTime+"，的数据获取失败，请添加对应分类");
                acceptLog.setState("0");
                System.out.println("接口调用失败，请请添加对应分类！！！！！");
                logMapper.insert(acceptLog);
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "接口调用失败", null);
            }else{
                acceptLog.setDescribes(startTime+"至"+endTime+"，的数据获取失败");
                acceptLog.setState("0");
                System.out.println("接口调用失败！！！！！");
                logMapper.insert(acceptLog);
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "接口调用失败", null);
            }


        }catch (Exception e){
            e.printStackTrace();
            acceptLog.setDescribes(startTime+"至"+endTime+"，的数据获取失败");
            acceptLog.setState("0");
            logMapper.insert(acceptLog);
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常，请联系管理员", null);
        }
        acceptLog.setDescribes(startTime+"至"+endTime+"，的数据获取成功");
        acceptLog.setState("1");
        logMapper.insert(acceptLog);

        //删除临时文件，防止系统内存不够用
        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);
        String deletePath=ossDir+"/ws/";
        String wsDownloadPath=ossDir+"/wsDownload/";
        File wsFile=new File(deletePath);
        if (wsFile.exists()){
            try {
                FileUtils.deleteDirectory(wsFile);
            }catch (IOException io){
                io.printStackTrace();
            }
        }

        File wsDownloaFile=new File(wsDownloadPath);
        if (wsDownloaFile.exists()){
            try {
                FileUtils.deleteDirectory(wsDownloaFile);
            }catch (IOException io){
                io.printStackTrace();
            }
        }


        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);

    }

    @ApiOperation("或者文水归档日志")
    @GetMapping("/log")
    public Result<PageInfo<ArchivesAcceptLog>> listLog(Integer pageNum,Integer pageSize,
                                                       @ApiParam("创建时间") String createTime,
                                                       @ApiParam("状态 0代表失败，1代表成功") String state){

        Page<ArchivesAcceptLog> page = new Page<>(pageNum == null ? 0 : pageNum,
                pageSize == null ? 10 : pageSize);

        QueryWrapper<ArchivesAcceptLog> queryWrapper=new QueryWrapper<>();
        if(!StringUtils.isEmpty(createTime)){
            queryWrapper.eq("createTime",createTime.substring(0,11));
        }
        queryWrapper.eq("type","ws");
        if(!StringUtils.isEmpty(state)){
            queryWrapper.eq(!StringUtils.isEmpty(state),"state",state);
        }

        queryWrapper.orderByDesc("createTime");

        IPage<ArchivesAcceptLog> info =logMapper.selectPage(page,queryWrapper);
        PageInfo<ArchivesAcceptLog> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(),
                info.getRecords());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
    }

    /*@GetMapping("/topdf")
    public String toPdf(){
        ToPdfUtil.doc2pdf("/home/jar/data/1.doc", "/home/jar/data/1.pdf");
        return "完毕";
    }*/

    @ApiOperation("在同步内蒙系统时，修改分类树使用")
    @GetMapping("/update/treeStr")
    public String updateTreeStr(){

        //部署内蒙系统，同步数据库时使用，与ArchivesClassMapper类的getTreeStr(long id)方法配套使用
        QueryWrapper<ArchivesClass> classQueryWrapper=new QueryWrapper<>();
        classQueryWrapper.notIn("parentId","0");
        List<ArchivesClass> list= archivesClassMapper.selectList(classQueryWrapper);

        //获取classType值为2的，所有classNum
        QueryWrapper<ArchivesClass> classTypeQueryWrapper=new QueryWrapper<>();
        classTypeQueryWrapper.select("distinct classNum");
        classTypeQueryWrapper.eq("classType","2");
        List<ArchivesClass> classNumList= archivesClassMapper.selectList(classTypeQueryWrapper);

        for (ArchivesClass archivesClass:list) {
            String treeStr= archivesClassMapper.getTreeStr(archivesClass.getId());
            for(int i=0;i<classNumList.size();i++){
                if(classNumList.get(i)!=null && !StringUtils.isEmpty(classNumList.get(i).getClassNum())){
                    String classNum="·"+classNumList.get(i).getClassNum();
                    if(treeStr.contains(classNum)){
                        treeStr=treeStr.replace(classNum,"");
                    }

                }
            }
            treeStr=treeStr.replace("··","·");
            archivesClass.setTreeStr(treeStr);

            QueryWrapper<ArchivesClass> classWrapper=new QueryWrapper<>();
            classWrapper.eq("classType","1");
            classWrapper.eq("id",archivesClass.getId());
            archivesClassMapper.update(archivesClass,classWrapper);
        }
        return "完毕";
    }

    /*@GetMapping("/down")
    public String downFtpFile(){
        try{
            Ftp ftp=new Ftp();
            ftp.setIpAddr("192.168.157.128");
            ftp.setPort(21);
            ftp.setUserName("ftptest");
            ftp.setPwd("ftptest");

            //ftp  下载测试

            String savePath="F:/zjq/图片/";
            String fileName="oa-lx-2152609820.zip";
            String downPath="/home/ftptest/lixi/OA/2023/2/4/";
            ftp.setPath(downPath);
            //FtpUtil.connectFtp(ftp);
            boolean is=FtpUtil.downFile(ftp,savePath,fileName);
            return "完成";
        }catch(Exception e){
            e.printStackTrace();
            return "发生错误";
        }finally {
            FtpUtil.closeFtp();
        }
    }*/
}
